<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Progress,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Textarea,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import StatisticsCard from '#/components/hotel/StatisticsCard.vue';

// 响应式数据
const loading = ref(false);
const showAddModal = ref(false);
const showDetailModal = ref(false);
const showItemsModal = ref(false);
const isEdit = ref(false);
const selectedStandard = ref<any>(null);
const selectedItems = ref<any[]>([]);

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: '',
});

// 标准表单
const standardForm = reactive({
  name: '',
  type: '',
  description: '',
  items: [],
  remarks: '',
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
});

// 标准数据
const standards = ref([
  {
    id: '1',
    name: '定期清洁标准',
    type: 'regular',
    status: 'active',
    description: '适用于日常定期清洁的质量检查标准',
    items: [
      { name: '地面清洁', category: 'floor', required: true, score: 20 },
      { name: '卫生间清洁', category: 'bathroom', required: true, score: 25 },
      { name: '厨房清洁', category: 'kitchen', required: true, score: 20 },
      { name: '卧室整理', category: 'bedroom', required: false, score: 15 },
      { name: '客厅清洁', category: 'living', required: false, score: 10 },
      { name: '阳台清洁', category: 'balcony', required: false, score: 10 },
    ],
    passRate: 92,
    createdAt: dayjs().subtract(30, 'day'),
    remarks: '基础清洁标准',
  },
  {
    id: '2',
    name: '退租清洁标准',
    type: 'checkout',
    status: 'active',
    description: '适用于退租时的深度清洁检查标准',
    items: [
      { name: '地面深度清洁', category: 'floor', required: true, score: 25 },
      {
        name: '卫生间深度清洁',
        category: 'bathroom',
        required: true,
        score: 30,
      },
      { name: '厨房深度清洁', category: 'kitchen', required: true, score: 25 },
      { name: '家具清洁', category: 'bedroom', required: true, score: 20 },
    ],
    passRate: 88,
    createdAt: dayjs().subtract(20, 'day'),
    remarks: '退租清洁要求较高',
  },
  {
    id: '3',
    name: '深度清洁标准',
    type: 'deep',
    status: 'active',
    description: '适用于季度深度清洁的检查标准',
    items: [
      { name: '地面抛光', category: 'floor', required: true, score: 30 },
      { name: '卫生间消毒', category: 'bathroom', required: true, score: 35 },
      { name: '厨房消毒', category: 'kitchen', required: true, score: 25 },
      { name: '家具保养', category: 'bedroom', required: true, score: 10 },
    ],
    passRate: 85,
    createdAt: dayjs().subtract(15, 'day'),
    remarks: '深度清洁标准',
  },
]);

// 统计信息
const statistics = computed(() => {
  const totalStandards = standards.value.length;
  const activeStandards = standards.value.filter(
    (s) => s.status === 'active',
  ).length;
  const totalItems = standards.value.reduce(
    (sum, s) => sum + s.items.length,
    0,
  );
  const avgPassRate =
    standards.value.reduce((sum, s) => sum + s.passRate, 0) /
    standards.value.length;

  return {
    totalStandards,
    activeStandards,
    totalItems,
    avgPassRate: avgPassRate.toFixed(1),
  };
});

// 过滤后的标准
const filteredStandards = computed(() => {
  let result = standards.value;

  if (searchForm.name) {
    result = result.filter((s) => s.name.includes(searchForm.name));
  }
  if (searchForm.type) {
    result = result.filter((s) => s.type === searchForm.type);
  }
  if (searchForm.status) {
    result = result.filter((s) => s.status === searchForm.status);
  }

  return result;
});

// 表格列定义
const columns = [
  {
    title: '标准名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '适用类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '检查项目',
    dataIndex: 'items',
    key: 'items',
    width: 120,
  },
  {
    title: '合格率',
    dataIndex: 'passRate',
    key: 'passRate',
    width: 150,
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 150,
    customRender: ({ text }: any) => formatDateTime(text),
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
];

// 检查项目表格列定义
const itemColumns = [
  {
    title: '项目名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '分类',
    dataIndex: 'category',
    key: 'category',
    width: 100,
  },
  {
    title: '必检',
    dataIndex: 'required',
    key: 'required',
    width: 80,
  },
  {
    title: '分值',
    dataIndex: 'score',
    key: 'score',
    width: 80,
  },
];

// 工具函数
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    active: 'success',
    inactive: 'default',
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '启用',
    inactive: '禁用',
  };
  return statusMap[status] || status;
};

const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    regular: 'blue',
    checkout: 'orange',
    deep: 'purple',
    emergency: 'red',
  };
  return colorMap[type] || 'default';
};

const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    regular: '定期清洁',
    checkout: '退租清洁',
    deep: '深度清洁',
    emergency: '紧急清洁',
  };
  return typeMap[type] || type;
};

const getCategoryText = (category: string) => {
  const categoryMap: Record<string, string> = {
    floor: '地面',
    bathroom: '卫生间',
    kitchen: '厨房',
    bedroom: '卧室',
    living: '客厅',
    balcony: '阳台',
  };
  return categoryMap[category] || category;
};

const getPassRateColor = (rate: number) => {
  if (rate >= 90) return '#52c41a';
  if (rate >= 80) return '#faad14';
  return '#ff4d4f';
};

const formatDateTime = (datetime: any) => {
  return datetime ? dayjs(datetime).format('YYYY-MM-DD HH:mm') : '';
  datetimedayjs.format;
};

// 事件处理函数
const handleSearch = () => {
  pagination.current = 1;
  console.log('搜索条件:', searchForm);
};

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    type: '',
    status: '',
  });
  pagination.current = 1;
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
};

const handleView = (record: any) => {
  selectedStandard.value = record;
  showDetailModal.value = true;
};

const handleViewItems = (record: any) => {
  selectedItems.value = record.items;
  showItemsModal.value = true;
};

const handleEdit = (record: any) => {
  isEdit.value = true;
  selectedStandard.value = record;
  Object.assign(standardForm, {
    name: record.name,
    type: record.type,
    description: record.description,
    items: [...record.items],
    remarks: record.remarks,
  });
  showAddModal.value = true;
};

const handleEnable = (record: any) => {
  message.success(`${record.name} 已启用`);
};

const handleDisable = (record: any) => {
  message.success(`${record.name} 已禁用`);
};

const handleDelete = (record: any) => {
  message.success(`${record.name} 已删除`);
};

const addItem = () => {
  standardForm.items.push({
    name: '',
    category: 'floor',
    required: false,
    score: 10,
  });
};

const updateItem = (index: number, field: string, value: any) => {
  standardForm.items[index][field] = value;
};

const removeItem = (index: number) => {
  standardForm.items.splice(index, 1);
};

const handleSave = () => {
  if (!standardForm.name || !standardForm.type) {
    message.error('请填写完整的标准信息');
    return;
  }

  if (standardForm.items.length === 0) {
    message.error('请至少添加一个检查项目');
    return;
  }

  if (isEdit.value) {
    message.success('标准更新成功');
  } else {
    message.success('标准添加成功');
  }

  showAddModal.value = false;
  handleCancel();
};

const handleCancel = () => {
  Object.assign(standardForm, {
    name: '',
    type: '',
    description: '',
    items: [],
    remarks: '',
  });
  isEdit.value = false;
  selectedStandard.value = null;
};

// 初始化
onMounted(() => {
  console.log('清洁标准设置页面已加载');
});
</script>

<template>
  <div class="cleaning-standards">
    <div class="page-header">
      <h2>清洁标准设置</h2>
      <Button type="primary" @click="showAddModal = true">
        <IconifyIcon icon="ant-design:plus-outlined" />
        添加标准
      </Button>
    </div>

    <!-- 搜索表单 -->
    <Card :bordered="false" class="search-card">
      <Form :model="searchForm" layout="inline">
        <FormItem label="标准名称">
          <Input
            :value="searchForm.name"
            placeholder="请输入标准名称"
            style="width: 150px"
            @input="(e) => (searchForm.name = e.target.value)"
          />
        </FormItem>
        <FormItem label="适用类型">
          <Select
            :value="searchForm.type"
            placeholder="请选择类型"
            style="width: 140px"
            allow-clear
            @change="(value) => (searchForm.type = value)"
          >
            <SelectOption value="regular">定期清洁</SelectOption>
            <SelectOption value="checkout">退租清洁</SelectOption>
            <SelectOption value="deep">深度清洁</SelectOption>
            <SelectOption value="emergency">紧急清洁</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="状态">
          <Select
            :value="searchForm.status"
            placeholder="请选择状态"
            style="width: 120px"
            allow-clear
            @change="(value) => (searchForm.status = value)"
          >
            <SelectOption value="active">启用</SelectOption>
            <SelectOption value="inactive">禁用</SelectOption>
          </Select>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="handleSearch">
            <IconifyIcon icon="ant-design:search-outlined" />
            搜索
          </Button>
          <Button @click="handleReset" style="margin-left: 8px">
            <IconifyIcon icon="ant-design:reload-outlined" />
            重置
          </Button>
        </FormItem>
      </Form>
    </Card>

    <!-- 统计卡片 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="总标准数"
          :value="statistics.totalStandards"
          color="#1890ff"
          icon="ant-design:setting-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="启用标准"
          :value="statistics.activeStandards"
          color="#52c41a"
          icon="ant-design:check-circle-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="检查项目"
          :value="statistics.totalItems"
          color="#faad14"
          icon="ant-design:audit-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="平均合格率"
          :value="statistics.avgPassRate"
          color="#722ed1"
          icon="ant-design:percentage-outlined"
        />
      </Col>
    </Row>

    <!-- 标准列表 -->
    <Card :bordered="false" class="table-card">
      <Table
        :columns="columns"
        :data-source="filteredStandards"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'type'">
            <Tag :color="getTypeColor(record.type)">
              {{ getTypeText(record.type) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'items'">
            <div class="items-info">
              <span class="items-count">{{ record.items.length }}项</span>
              <Button type="link" size="small" @click="handleViewItems(record)">
                查看
              </Button>
            </div>
          </template>
          <template v-else-if="column.key === 'passRate'">
            <div class="pass-rate">
              <Progress
                :percent="record.passRate"
                :stroke-color="getPassRateColor(record.passRate)"
                size="small"
                :show-info="false"
              />
              <span class="rate-text">{{ record.passRate }}%</span>
            </div>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="handleView(record)">
                查看
              </Button>
              <Button type="link" size="small" @click="handleEdit(record)">
                编辑
              </Button>
              <Button
                v-if="record.status === 'inactive'"
                type="link"
                size="small"
                @click="handleEnable(record)"
              >
                启用
              </Button>
              <Button
                v-if="record.status === 'active'"
                type="link"
                size="small"
                @click="handleDisable(record)"
              >
                禁用
              </Button>
              <Button
                type="link"
                size="small"
                danger
                @click="handleDelete(record)"
              >
                删除
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 添加/编辑标准弹窗 -->
    <Modal
      :open="showAddModal"
      :title="isEdit ? '编辑标准' : '添加标准'"
      width="800px"
      @ok="handleSave"
      @cancel="handleCancel"
    >
      <Form :model="standardForm" layout="vertical">
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="标准名称" name="name" required>
              <Input
                :value="standardForm.name"
                placeholder="请输入标准名称"
                @input="(e) => (standardForm.name = e.target.value)"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="适用类型" name="type" required>
              <Select
                :value="standardForm.type"
                placeholder="请选择适用类型"
                style="width: 100%"
                @change="(value) => (standardForm.type = value)"
              >
                <SelectOption value="regular">定期清洁</SelectOption>
                <SelectOption value="checkout">退租清洁</SelectOption>
                <SelectOption value="deep">深度清洁</SelectOption>
                <SelectOption value="emergency">紧急清洁</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <FormItem label="标准描述" name="description">
          <Textarea
            :value="standardForm.description"
            placeholder="请输入标准描述"
            :rows="3"
            @input="(e) => (standardForm.description = e.target.value)"
          />
        </FormItem>
        <FormItem label="检查项目" name="items">
          <div class="items-editor">
            <div class="items-header">
              <span>检查项目列表</span>
              <Button type="dashed" size="small" @click="addItem">
                <IconifyIcon icon="ant-design:plus-outlined" />
                添加项目
              </Button>
            </div>
            <div class="items-list">
              <div
                v-for="(item, index) in standardForm.items"
                :key="index"
                class="item-row"
              >
                <Row :gutter="8">
                  <Col :span="8">
                    <Input
                      :value="item.name"
                      placeholder="项目名称"
                      @input="(e) => updateItem(index, 'name', e.target.value)"
                    />
                  </Col>
                  <Col :span="6">
                    <Select
                      :value="item.category"
                      placeholder="分类"
                      style="width: 100%"
                      @change="(value) => updateItem(index, 'category', value)"
                    >
                      <SelectOption value="floor">地面</SelectOption>
                      <SelectOption value="bathroom">卫生间</SelectOption>
                      <SelectOption value="kitchen">厨房</SelectOption>
                      <SelectOption value="bedroom">卧室</SelectOption>
                      <SelectOption value="living">客厅</SelectOption>
                      <SelectOption value="balcony">阳台</SelectOption>
                    </Select>
                  </Col>
                  <Col :span="4">
                    <Select
                      :value="item.required"
                      placeholder="必检"
                      style="width: 100%"
                      @change="(value) => updateItem(index, 'required', value)"
                    >
                      <SelectOption :value="true">是</SelectOption>
                      <SelectOption :value="false">否</SelectOption>
                    </Select>
                  </Col>
                  <Col :span="4">
                    <Input
                      :value="item.score"
                      placeholder="分值"
                      type="number"
                      @input="
                        (e) =>
                          updateItem(index, 'score', parseInt(e.target.value))
                      "
                    />
                  </Col>
                  <Col :span="2">
                    <Button
                      type="text"
                      danger
                      size="small"
                      @click="removeItem(index)"
                    >
                      <IconifyIcon icon="ant-design:delete-outlined" />
                    </Button>
                  </Col>
                </Row>
              </div>
            </div>
          </div>
        </FormItem>
        <FormItem label="备注" name="remarks">
          <Textarea
            :value="standardForm.remarks"
            placeholder="请输入备注信息"
            :rows="2"
            @input="(e) => (standardForm.remarks = e.target.value)"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 标准详情弹窗 -->
    <Modal
      :open="showDetailModal"
      title="标准详情"
      width="800px"
      :footer="null"
    >
      <div v-if="selectedStandard" class="standard-detail">
        <Row :gutter="16">
          <Col :span="12">
            <div class="detail-section">
              <h4>基本信息</h4>
              <div class="detail-item">
                <span class="label">标准名称：</span>
                <span class="value">{{ selectedStandard.name }}</span>
              </div>
              <div class="detail-item">
                <span class="label">适用类型：</span>
                <span class="value">
                  <Tag :color="getTypeColor(selectedStandard.type)">
                    {{ getTypeText(selectedStandard.type) }}
                  </Tag>
                </span>
              </div>
              <div class="detail-item">
                <span class="label">状态：</span>
                <span class="value">
                  <Tag :color="getStatusColor(selectedStandard.status)">
                    {{ getStatusText(selectedStandard.status) }}
                  </Tag>
                </span>
              </div>
              <div class="detail-item">
                <span class="label">创建时间：</span>
                <span class="value">{{
                  formatDateTime(selectedStandard.createdAt)
                }}</span>
              </div>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-section">
              <h4>统计信息</h4>
              <div class="detail-item">
                <span class="label">检查项目：</span>
                <span class="value">{{ selectedStandard.items.length }}项</span>
              </div>
              <div class="detail-item">
                <span class="label">必检项目：</span>
                <span class="value"
                  >{{
                    selectedStandard.items.filter((i) => i.required).length
                  }}项</span
                >
              </div>
              <div class="detail-item">
                <span class="label">总分值：</span>
                <span class="value"
                  >{{
                    selectedStandard.items.reduce((sum, i) => sum + i.score, 0)
                  }}分</span
                >
              </div>
              <div class="detail-item">
                <span class="label">合格率：</span>
                <span class="value">{{ selectedStandard.passRate }}%</span>
              </div>
            </div>
          </Col>
        </Row>
        <div class="detail-section">
          <h4>标准描述</h4>
          <div class="detail-item">
            <span class="value">{{
              selectedStandard.description || '无描述'
            }}</span>
          </div>
        </div>
        <div class="detail-section">
          <h4>检查项目</h4>
          <Table
            :columns="itemColumns"
            :data-source="selectedStandard.items"
            :pagination="false"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'category'">
                <Tag color="blue">{{ getCategoryText(record.category) }}</Tag>
              </template>
              <template v-else-if="column.key === 'required'">
                <Tag :color="record.required ? 'red' : 'default'">
                  {{ record.required ? '是' : '否' }}
                </Tag>
              </template>
            </template>
          </Table>
        </div>
        <div v-if="selectedStandard.remarks" class="detail-section">
          <h4>备注</h4>
          <div class="detail-item">
            <span class="value">{{ selectedStandard.remarks }}</span>
          </div>
        </div>
      </div>
    </Modal>

    <!-- 检查项目弹窗 -->
    <Modal
      :open="showItemsModal"
      title="检查项目详情"
      width="600px"
      :footer="null"
    >
      <div v-if="selectedItems" class="items-detail">
        <Table
          :columns="itemColumns"
          :data-source="selectedItems"
          :pagination="false"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'category'">
              <Tag color="blue">{{ getCategoryText(record.category) }}</Tag>
            </template>
            <template v-else-if="column.key === 'required'">
              <Tag :color="record.required ? 'red' : 'default'">
                {{ record.required ? '是' : '否' }}
              </Tag>
            </template>
          </template>
        </Table>
      </div>
    </Modal>
  </div>
</template>

<style scoped>
.cleaning-standards {
  padding: 16px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.search-card {
  margin-bottom: 24px;
}

.statistics-row {
  margin-bottom: 24px;
}

.table-card {
  margin-bottom: 24px;
}

.items-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.items-count {
  font-weight: 600;
  color: #1890ff;
}

.pass-rate {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rate-text {
  font-size: 12px;
  color: #666;
  min-width: 40px;
}

.items-editor {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  padding: 16px;
}

.items-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  font-weight: 500;
}

.items-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.item-row {
  padding: 12px;
  background: #fafafa;
  border-radius: 4px;
}

.standard-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin-bottom: 12px;
  color: #1f2937;
  font-weight: 600;
}

.detail-item {
  display: flex;
  margin-bottom: 8px;
  align-items: center;
}

.detail-item .label {
  width: 100px;
  color: #666;
  font-weight: 500;
}

.detail-item .value {
  flex: 1;
  color: #1f2937;
}

.items-detail {
  max-height: 400px;
  overflow-y: auto;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background-color: #fafafa;
}

:deep(.ant-progress-bg) {
  height: 6px;
}
</style>
